/* global window */
import axios from 'axios';
import qs from 'qs';
import jsonp from 'jsonp';
import lodash from 'lodash';
import pathToRegexp from 'path-to-regexp';
import {message} from 'antd';
import {YQL, CORS} from './config';
/**
 * 配置axios
 */
const axiosInstance = axios.create({withCredentials: true});
/**
 *兼容IE路由跳转
 */
function getContextPath () {
    let pathName = document.location.pathname;
    let index = pathName.substr(1).indexOf("/");
    let result = pathName.substr(0,index+1);
    return result;
}
/**
 * 转换请求体结构
 */
const getContentData = (contentType, httpType, cloneData) => {
    switch (contentType) {
    case 'application/x-www-form-urlencoded': {
        let params = '';
        for (const key in cloneData) {
            if (cloneData.hasOwnProperty(key)) {
                params += `${key}=${cloneData[key]}&`;
            }
        }
        return params.substr(0, params.length - 1);
    }
    case 'multipart/form-data': {
        const formData = new FormData();
        for (const key in cloneData) {
            if (cloneData.hasOwnProperty(key)) {
                formData.append(key, cloneData[key]);
            }
        }
        return formData;
    }
    case 'application/json':
        return JSON.stringify(cloneData);
    default:
        return cloneData;
    }
};

const fetch = (options) => {
    let {
        method = 'get',
        data,
        fetchType,
        contentType,
        url,
    } = options;

    const cloneData = lodash.cloneDeep(data);

    try {
        let domin = '';
        if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
            [domin] = url.match(/[a-zA-z]+:\/\/[^/]*/);
            url = url.slice(domin.length);
        }
        const match = pathToRegexp.parse(url);
        url = pathToRegexp.compile(url)(data);
        for (const item of match) {
            if (item instanceof Object && item.name in cloneData) {
                delete cloneData[item.name];
            }
        }
        url = domin + url;
    } catch (e) {
        message.error(e.message);
    }

    if (fetchType === 'JSONP') {
        return new Promise((resolve, reject) => {
            jsonp(url, {
                param: `${qs.stringify(data)}&callback`,
                name: `jsonp_${new Date().getTime()}`,
                timeout: 4000,
            }, (error, result) => {
                if (error) {
                    reject(error);
                }
                resolve({statusText: 'OK', status: 200, data: result});
            });
        });
    } else if (fetchType === 'YQL') {
        url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`;
        data = null;
    }
    console.log('请求数据：=>', cloneData);
    switch (method.toLowerCase()) {
    case 'get':
        return axiosInstance.get(url, {
            params: cloneData,
        });
    case 'delete':
        return axiosInstance.delete(url, {
            data: cloneData,
        });
    case 'post':
        return axiosInstance.post(url, getContentData(contentType, 'post', cloneData), {
            headers: {
                'Content-Type': contentType,
            },
        });
    case 'put':
        return axiosInstance.put(url, getContentData(contentType, 'put', cloneData), {
            headers: {
                'Content-Type': contentType,
            },
        });
    case 'patch':
        return axiosInstance.patch(url, getContentData(contentType, cloneData), {
            headers: {
                'Content-Type': contentType,
            },
        });
    default:
        return axiosInstance(options);
    }
};

export default function requestWork (options) {

    if (options.url && options.url.indexOf('//') > -1) {
        const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`;
        if (window.location.origin !== origin) {
            if (CORS && CORS.indexOf(origin) > -1) {
                options.fetchType = 'CORS';
            } else if (YQL && YQL.indexOf(origin) > -1) {
                options.fetchType = 'YQL';
            } else {
                options.fetchType = 'JSONP';
            }
        }
    }
    return fetch(options).then((response) => {
        const {statusText, status} = response;
        let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data;
        if (data instanceof Array) {
            data = {
                list: data,
            };
        }
        console.log('返回数据：=>', response);
        // const {code,id, message:msg} = data;
        // if (code === 2 || code === 3 ) {
        //     // 没有登录，需要登录
        //     console.log(window.location.pathname);
        //     //ie 解决window.location.href报错404（兼容ie） ===>跳转登录
        //     window.location.href = getContextPath()+"/login";
        //     return Promise.resolve({});
        // } else if (code !== 0 && !id) {
        //     message.error(msg);
        // }
        return Promise.resolve({
            success: true,
            message: statusText,
            statusCode: status,
            ...data,
        });
    }).catch((error) => {
        const {response} = error;
        console.log('错误返回：=>', response);
        let msg;
        let statusCode;
        if (response && response instanceof Object) {
            const {data, statusText} = response;
            statusCode = response.status;
            msg = data.message || statusText;
        } else {
            statusCode = 600;
            msg = error.message || 'Network Error';
        }

        /* eslint-disable */
        return Promise.reject({success: false, statusCode, message: msg})
    })
}
